/**
 * Created by sunkejun on 2015/10/15.
 */

$(document).ready(function(){
    var table = new ComDataTable("/admin/ad_position/page",$('#dataTable'),"admin_ad_position");
    var renders = {
        id:admin_ad_position_list.editRender,
        position:admin_ad_position_list.positonRender,
    };
    table.setRenders(renders);
    table.init();
    admin_ad_position_list.$table=table;
    admin_ad_position_list.initSteps();
    admin_ad_position_list.initSelectable();
})
var admin_ad_position_list  = (function ($) {
    this.editRender = function( data, type, full, meta ) {
        return   '<div>  <button class="btn btn-sm btn-warning"      onclick="admin_ad_position_list.editTarget('+data+')">  <span class="fa fa-edit"></span></button>'+
            '&nbsp; <button class="btn btn-sm btn-danger"      onclick="admin_ad_position_list.delete('+data+')">  <span class="fa fa-trash"></span></button></div> ';
    }
    this.positonRender = function( data, type, full, meta ) {
        var spdatas =[];
        if(data){
            spdatas = data.split("|");
        }
        str = '<div id="renderSelect"   class="col-sm-12"  >';

        for($i=0;$i<8;$i++){
            for($j=0;$j<6;$j++){
                var id = $i+'-'+$j;
                if(spdatas.indexOf(id) != -1){
                    str+= "<div   class='col-sm-2 ui-selected' style='height: 20px;border: 1px solid red '></div>";
                }else{
                    str+= "<div   class='col-sm-2' style='height: 20px;border: 1px solid red '></div>";
                }

            }
        }
        str+=   '</div>';

        return str;
    }



    this.delete = function(id){
        swal({
            title: language.getNorlanguage().delete_title,
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: language.getNorlanguage().delete_sub,
            cancelButtonText: language.getNorlanguage().delete_cancle,
            closeOnConfirm: true,
            html: false
        }, function(){
            ComdataUtil.ajaxpostnormal('/admin/ad_position/'+id,{},function(data){
                this.$table.rdraw();
            },"DELETE");
        });
    }


    this.submit = function(){
        $('#com_message').html("");
        var data = ComdataUtil.collectData("actionmodifyform");
        ComdataUtil.ajaxpost('/admin/ad_position',data,this.finishAjaxLoadBack);
    }

    this.initSteps = function(){
        this.$step =  $("#actionmodifyform").steps({
            bodyTag: "fieldset",
            labels:language.getSetpLanguage(),
            onStepChanging: function (event, currentIndex, newIndex)
            {
                // Always allow going backward even if the current step contains invalid fields!
                if (currentIndex > newIndex)
                {
                    return true;
                }
                var form = $(this);

                // Clean up if user went backward before
                if (currentIndex < newIndex)
                {
                    // To remove error styles
                    $(".body:eq(" + newIndex + ") label.error", form).remove();
                    $(".body:eq(" + newIndex + ") .error", form).removeClass("error");
                }

                // Disable validation on fields that are disabled or hidden.
                form.validate().settings.ignore = ":disabled,:hidden";

                // Start validation; Prevent going forward if false
                return form.valid();
            },
            onStepChanged: function (event, currentIndex, priorIndex)
            {
                // Suppress (skip) "Warning" step if the user is old enough and wants to the previous step.
                if (currentIndex >= 2)
                {
                    $(this).steps("previous");
                }
            },
            onFinishing: function (event, currentIndex)
            {
                var form = $(this);
                form.validate().settings.ignore = ":disabled";
                return form.valid();
            },
            onFinished: function (event, currentIndex)
            {
                var form = $(this);
                admin_ad_position_list.submit();
            },
            onCanceled: function (event) {
                admin_ad_position_list.closeModel();
            },
        }).validate({
            errorPlacement: function (error, element)
            {
                element.before(error);
            },
            rules: {
                name: "required",
                positions: "required",
            },
            messages: {
                name: "请输入名称",
                positions: "请选出广告位置信息",
            }
        });

    }
    this.openAdd = function(){
        openModel(0);



    }


    this.addNew = function(){
        openModel(0);
    }
    this.getItem = function(item){
        //openModel();
        ComdataUtil.loadContainer("actionmodifyform",item);
        this.setSelectable(item.position);
    }
    this.editTarget = function(id){
        openModel();
        ComdataUtil.ajaxpostnormal('/admin/ad_position/'+id,{},this.getItem,"GET");

    }

    this.openModel = function(type) {
        $("#actionmodifyform").steps("previous");
        admin_ad_position_list.clearSelectable();
        ComdataUtil.clear("actionmodifyform");
        $("#ad_position_modal").modal('show');

    }


    this.setSelectable = function(data){
        if(data == null){
            return ;
        }
        var isdatas = data.split("|");
        $("#selectable div").each(function(){
            if(isdatas.indexOf($(this).attr('id')) != -1){
                $(this).addClass('ui-selected');
            }
        });
    }
    /**
     * 重置selectable
     */
    this.clearSelectable = function(){
        $("#selectable div").each(function(){
            $(this).removeClass('ui-selected');
        });
    }
    this.initSelectable = function(){
        $( "#selectable" ).selectable({
            create:function(){
                admin_ad_position_list.clearSelectable();
            },
            stop: function( event, ui ) {
                var sel = "";
                $("#selectable div").each(function(){
                    if($(this).hasClass('ui-selected')){
                        if(sel != ""){
                            sel+="|";
                        }
                        sel+=$(this).attr('id');
                    }
                });
                $("#position").val(sel);
            }
        });
    }
    this.closeModel = function() {
        $("#ad_position_modal").modal('hide');
    }


    this.submit = function(){
        $('#com_message').html("");
        var data = ComdataUtil.collectData("actionmodifyform");
        ComdataUtil.ajaxpost('/admin/ad_position',data,this.finishAjaxLoadBack);
    }

    this.view = function(id){
        $("#ad_prview").modal('show');
        $("#view_container").html("");
        ComdataUtil.ajaxpostnormal('/admin/ad_position/'+id,{},function(data){
            $("#view_container").html(data.ad_content);
        },"GET");
    }
    this.finishAjaxLoadBack = function(response){
        if(response.code == 500){
            $('#com_message').attr("class","text-danger text-center");
            $('#com_message').html(response.res_data);
        }else{
            ComdataUtil.clear("actionmodifyform");
            closeModel();
            this.$table.rdraw();
        }

    }
    return this;
})(jQuery);

